package cn.remex.core.quartz;

import cn.remex.RemexConstants;
import cn.remex.core.exception.ServiceCode;
import cn.remex.core.util.Assert;
import cn.remex.core.util.MapHelper;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.quartz.TriggerKey;
import org.quartz.impl.StdSchedulerFactory;
import org.quartz.impl.matchers.GroupMatcher;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;


/**
 * @author liuhengyang 
 * date 2014-10-14 上午11:58:38
 * @version 版本号码
 */
public final class SchedulerManager {
	static final StdSchedulerFactory schedulerFactory = new StdSchedulerFactory();
	public static void stopAll() {
		for (org.quartz.Scheduler scheduler : getAllSchedulers()) {
			Object schedulerName = "Cannot obtain SchedulerName";
			try {
				schedulerName = scheduler.getSchedulerName();
				scheduler.shutdown();
			} catch (SchedulerException e) {
				RemexConstants.logger.debug(ServiceCode.QUARTZ_ERROR, "关闭所有日程时，关闭{}日程出错",schedulerName);
			}
		}
	}
	public static Scheduler getDefaultScheduler() {
		return getScheduler("DefaultQuartzScheduler");//配置文件中制定的那个日程安排，不配置默认为此
	}
	public static Scheduler getScheduler(String schedulerName) {

		org.quartz.Scheduler scheduler;
		try {
			scheduler = "DefaultQuartzScheduler".equals(schedulerName)?SchedulerManager.schedulerFactory.getScheduler():SchedulerManager.schedulerFactory.getScheduler(schedulerName);
			Assert.notNull(scheduler, ServiceCode.QUARTZ_ERROR, "没有配置指定的日程表，schedulerName={}" + schedulerName);

			schedulerName = scheduler.getSchedulerName();
		} catch (SchedulerException e) {
			throw new QuartzException(ServiceCode.QUARTZ_ERROR, "创建SchedulerHandler失败！", e);
		}

		return new Scheduler(schedulerName, scheduler);
	}
	public static Collection<org.quartz.Scheduler> getAllSchedulers() {
		try {
			return schedulerFactory.getAllSchedulers();
		} catch (SchedulerException e) {
			throw new QuartzException(ServiceCode.QUARTZ_ERROR, "无法获取所有任务日程", e);
		}
	}

	public static List<String> getAllSchedulerNames() {
		List<String> schedulerNames = new ArrayList<>();
		try {
			for (org.quartz.Scheduler scheduler : getAllSchedulers()) {
				schedulerNames.add(scheduler.getSchedulerName());
			}
		} catch (SchedulerException e) {
			throw new QuartzException(ServiceCode.QUARTZ_ERROR, "无法获取日程名称", e);
		}
		return schedulerNames;
	}

	public static List<Map<String,Object>> getJobs(String schedulerName){
		//暂时只查默认scheduler的脚本
		List<Map<String, Object>> jobInfoMap = new ArrayList<>();
		try {
			org.quartz.Scheduler scheduer = getDefaultScheduler().getScheduler();
			List<String> jobGroups = scheduer.getJobGroupNames();
			List<String> triggerGroups = scheduer.getTriggerGroupNames();

			for (String groupName: triggerGroups){
				Set<TriggerKey> jobKeys = scheduer.getTriggerKeys(GroupMatcher.groupEquals(groupName));
				for (TriggerKey jobKey : jobKeys) {
					Trigger job = scheduer.getTrigger(jobKey);
					Map<String, Object> jobAndTrigger = MapHelper.toMap(job,String::valueOf);
					jobAndTrigger.put("mayFireAgain", job.mayFireAgain());
					jobInfoMap.add(jobAndTrigger);
				}
			}

		} catch (Exception e) {
			throw new QuartzException(ServiceCode.QUARTZ_ERROR, "无法获取当前job列表", e);
		}
		return jobInfoMap;

	}

	public static Object removeJob(String triggerKey) {
		getDefaultScheduler().deleteTask(triggerKey);
		return "OK";
	}
}


